import React, {useState, useEffect, useRef} from 'react';
import { getNewsList } from '../../../api/news';
import formatTime from '@/util/format'
import { List, Image, Skeleton } from 'antd-mobile'
import { FireFill } from 'antd-mobile-icons'
import styled from 'styled-components'
import { useNavigate } from 'react-router-dom';

const Container = styled.div`
  & {
    height: 100%;
    overflow: scroll;
  }
`

const filter = (num = 0) => {
  if (isNaN(num)) return 'NaN';
  num = num + ''
  // 亿
  if (num.length >= 9) return + (num.slice(-num.length, -8) + '.' + num.at(num.length - 8)) + '亿'
  // 万
  else if (num.length >= 5) return + (num.slice(-num.length, -4) + '.' + num.at(num.length - 4)) + '万'
  else return num
}

const Right = ({data}) => {
  return (
    <div>
      <FireFill color='#ff701c' />
      <span style={{'fontSize': '12px'}}>{filter(data.post_hot) || 0}</span>
    </div>
  )
}


const News = () => {
  const naviget = useNavigate()  
  const [list, setlist] = useState([]);
  useEffect( async () => {
    let isMounted = true
    const params = {
      near: 1
    }
    const rows = await getNewsList(params)
    if (isMounted) setlist(rows)
    return () => {isMounted = false}
  }, [])
  // 注意：空的依赖数组 []
  // 表示这个 useEffect
  // 与 componentDidMount() 类似，只运行一次
  return (
    <Container>
    <div>
      {
        list && list.data && list.data.length > 0
        ? '':
        (<div>
          <Skeleton.Title animated />
          <Skeleton.Paragraph lineCount={10} animated />
        </div>)
      }
      {
        <List>
          {list && list.data && list.data.map((item, index) => (
            <List.Item
              key={index}
              onClick={() => naviget('/frameDetail', {state: {datas: item}})}
              prefix={
                <Image
                  src={item.src || require('@/static/image/morent.png')}
                  width={120}
                  height={80}
                />
              }
              extra={
                <Right data={item}></Right>
              }
              description={'时间: ' + item.update_time} 
            >
              {item.post_title}
            </List.Item>
          ))}
        </List>
      }
    </div>
    </Container>
  );
}

export default News;
